import { defineStore } from 'pinia'
import axios from 'axios'

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [],
    total: 0
  }),

  actions: {
    async fetchCart() {
      try {
        const token = localStorage.getItem('token')
        const response = await axios.get('http://localhost:3000/api/cart', {
          headers: { Authorization: `Bearer ${token}` }
        })
        this.items = response.data
        this.calculateTotal()
      } catch (error) {
        console.error('获取购物车失败:', error)
      }
    },

    async addToCart(productId, quantity = 1) {
      try {
        const token = localStorage.getItem('token')
        await axios.post('http://localhost:3000/api/cart/add', 
          { productId, quantity },
          { headers: { Authorization: `Bearer ${token}` } }
        )
        await this.fetchCart()
      } catch (error) {
        console.error('添加商品到购物车失败:', error)
      }
    },

    async updateQuantity(itemId, quantity) {
      try {
        const token = localStorage.getItem('token')
        await axios.put(`http://localhost:3000/api/cart/${itemId}`,
          { quantity },
          { headers: { Authorization: `Bearer ${token}` } }
        )
        await this.fetchCart()
      } catch (error) {
        console.error('更新购物车商品数量失败:', error)
      }
    },

    async removeItem(itemId) {
      try {
        const token = localStorage.getItem('token')
        await axios.delete(`http://localhost:3000/api/cart/${itemId}`, {
          headers: { Authorization: `Bearer ${token}` }
        })
        await this.fetchCart()
      } catch (error) {
        console.error('删除购物车商品失败:', error)
      }
    },

    async clearCart() {
      try {
        const token = localStorage.getItem('token')
        await axios.delete('http://localhost:3000/api/cart', {
          headers: { Authorization: `Bearer ${token}` }
        })
        this.items = []
        this.total = 0
      } catch (error) {
        console.error('清空购物车失败:', error)
      }
    },

    calculateTotal() {
      this.total = this.items.reduce((sum, item) => {
        return sum + (item.price * item.quantity)
      }, 0)
    }
  }
}) 